package
{
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.TimerEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	import spark.components.Label;
	
	import utils.ColorUtil;
	
	/**
	 * MORN UI转LAYA UI
	 */
	public class UITransfer
	{
		private static var _ins:UITransfer;
		
		public var printMsg:Label;
		public var importRoot:String;
		public var exportUrl:String;
		
		private var _loadList:Array = [];//需要加载的文件列表
		private var _contentList:Array = [];//已经加载好的 文本内容列表
		private var _count:int = 0;
		private var _maxCount:int = 0;
		private var _cfgStream:FileStream;
		
		private var _outObjArr:Array;
		
		private var _timer:Timer;
		
		private static var SELECTEID:int = 20;//全局UI文件的ID
		private var _posX:int = 0;//匹配LAYAUI的第一个“x”
		private var _compId:int = 1;
		
		public static function get ins():UITransfer
		{
			if(!_ins){
				_ins = new UITransfer();
			}
			return _ins;
		}
		public function get running():Boolean
		{
			return Boolean(_loadList.length > 0);
		}
		
		public function UITransfer()
		{
			_cfgStream = new FileStream();
			
			_timer = new Timer(100);
			_timer.addEventListener(TimerEvent.TIMER, onTimer);
		}
		/**
		 * 设置文件列表
		 */
		public function setList(list:Array):void
		{
			_loadList = list;	
			_maxCount = list.length;
			_count = 0;
		}
		/**
		 * 启动开始加载，需先调用 setList
		 */
		public function startLoad():void
		{
			_contentList.length = 0;
			nextLoad();
		}
		private function nextLoad():void
		{
			if(_loadList.length)
			{
				var url:String = _loadList.shift();
				var loader:TextLoader = new TextLoader();
				loader.url = url;
				loader.dataFormat = URLLoaderDataFormat.TEXT;
				loader.addEventListener(Event.COMPLETE, handleComplate);
				loader.addEventListener(IOErrorEvent.IO_ERROR, handleComplate);
				loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
				loader.load(new URLRequest(url));
			}
			else
			{
				//开始输出新文件
				if(!_timer.running)
				{
					_timer.start();
				}
				_count = 0;
				_maxCount = _contentList.length;
			}
		}
		private function handleComplate(e:Event):void
		{
			trace("UI-加载成功！url=" + e.target.url);
			var testpath:String = e.target.url;
			if(testpath.indexOf("EquipGetPromptPanel") != -1){
				trace("测试" + e.target.data);
			}
			
			var loader:TextLoader = e.target as TextLoader;
			loader.removeEventListener(Event.COMPLETE, handleComplate);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, handleComplate);
			loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, handleHttpStatus);
			
			_contentList.push(loader);
			
			_count ++;
			printMsg.text = "正在加载：" + _count + "/" + _maxCount + "   url=" + loader.url;
			
			nextLoad();
		}
		private function handleHttpStatus(e:HTTPStatusEvent):void
		{
			if(e.status >= 400){
				trace("UI-404错误！url=" + e.target.url);
			}
		}
		private function onTimer(e:TimerEvent):void
		{
			if(_contentList.length)
			{
				var loader:TextLoader = _contentList.shift();
				writeLayaUI(loader);
			}
			else
			{
				_timer.stop();
			}
		}
		public function writeLayaUI(loader:TextLoader):void
		{
			SELECTEID ++;
			
			var path:String;
			var txtStr:String;
			var hz:String;
			var url:String = loader.url;
			
			var startIndex:int = url.lastIndexOf("/");
			var endIndex:int = url.length;
			var dic2:String = url.substring(startIndex+1, endIndex);
			var dicStart:int = importRoot.lastIndexOf("/");
			var dicEnd:int = startIndex;
			var dic:String = url.substring(dicStart+1, dicEnd);
			if(dic == "")
			{
				path = dic + dic2;
			}
			else
			{
				path = dic + "/" + dic2;
			}
			path = path.replace(".xml", ".ui");
			
			var rootFile:File = new File(exportUrl);
			var fl:File = rootFile.resolvePath(path);
//			try
//			{
				_count ++;
				if(_count >= _maxCount){
					printMsg.text = "转换完成：" + _count + "/" + _maxCount + "   url=" + path;
				}
				else{
					printMsg.text = "正在转换：" + _count + "/" + _maxCount + "   url=" + path;
				}
				
				_outObjArr = [];
				transferXML(loader.data, _outObjArr);
				
				var obj:Object = {root:_outObjArr};
				if(_outObjArr[0] == null){//空文件，不处理。
					return;
				}
				var str:String = JSON.stringify(_outObjArr[0]);
				
				//还原之前的转义，主要针对text赋值
				str = str.replace(/&lt;/gi, "<");
				str = str.replace(/&gt;/gi, ">");
				str = str.replace(/&quot;/gi, "\\\"");//引号替换
				
				_cfgStream.open(fl, FileMode.WRITE);
				_cfgStream.writeUTFBytes(str);
				_cfgStream.close();
//			}
//			catch(e:Error)
//			{
//				throw new Error(e.getStackTrace());
//			}
		}
		private function transferXML(xml:String, arr:Array):void
		{
			xml = xml.replace(/<Container/gi, "<Sprite");
			xml = xml.replace(/<\/Container/gi, "<\/Sprite");
			
			xml = xml.replace(/<RadioButton/gi, "<Radio");
			xml = xml.replace(/<\/RadioButton/gi, "<\/Radio");
			
			xml = xml.replace(/br\/>/gi, "");
			xml = xml.replace(/&#xA;/gi, "");
			
			
			var startIndex:int = 0;
			while(true)
			{
				var index:int = xml.indexOf("<", startIndex);
				var index2:int = xml.indexOf(" ", index + 1);
				var tag:String = xml.substring(index + 1, index2);
				var indexEnter:int = xml.indexOf("\n", index + 1);
				var singleIndex:int = xml.indexOf("/>", index + 1);
				var obj:Object;
				var str:String;
				
				if(index == -1)
				{
					break;
				}
				
				str = xml.substring(index, indexEnter);
				if(str.indexOf("/>") == -1)
				{
					str = str.replace(">", "/>");
				}
				
				var xmllist1:XML = new XML(str);
				var ssl:int;
				var xl:XMLList = xmllist1.attributes();
				var qname:QName;
				var attrName:String = xmllist1.attribute("sceneWidth");
				var attrValue:*;
				var valueStr:String;
				var propsStr:String = "";
				var isInt:Boolean = false;
				var varName:String = "";
				var viewSource:String = "";
				for(var i:int=0; i<xl.length(); i++)
				{
					qname = xl[i].name();
					attrName = qname.localName;
					attrValue = xmllist1.attribute(attrName);
					valueStr = attrValue.toString();
					
					var labelStrokeColorStr:String = "";//兼容flash按钮描边
					
					if(attrName=="color"){
						valueStr = ColorUtil.toHexColor(parseInt(valueStr));
					}
					if(valueStr && valueStr.indexOf("0x") != -1)
					{
						valueStr = valueStr.replace("0x", "#");
					}
					if(attrName == "url"){
						attrName = "skin";
					}
					//放在上一段代码的后面
					if(attrName == "sceneWidth"){
						attrName = "width";
					}
					else if(attrName == "sceneHeight"){
						attrName = "height";
					}
					else if(attrName == "stroke"){
						valueStr = "1";
					}
					else if(attrName == "var"){
						varName = valueStr;
					}
					else if(attrName == "sceneColor"){
						valueStr = "#000000";
					}
					else if(attrName == "skin"){
						if(valueStr.indexOf("png.") != -1){
							valueStr = valueStr.replace("png.", "");
							valueStr = valueStr.replace(/\./gi, "/");
							valueStr = valueStr + ".png";
						}
						else if(valueStr.indexOf("jpg.") != -1){
							valueStr = valueStr.replace("jpg.", "");
							valueStr = valueStr.replace(/\./gi, "/");
							valueStr = valueStr + ".jpg";
						}
						if(valueStr.indexOf("&quot;") != -1 || valueStr.indexOf("\"") != -1){
							trace("什么贵");
							valueStr = valueStr.replace(/\&quot;/gi, " ");//&quot;是转义符，得转成  ，否则会报错
							valueStr = valueStr.replace(/\"/gi, " ");//&quot;是转义符，得转成  ，否则会报错
						}
						valueStr = "mobile/" + valueStr;
						valueStr = getLayaSkin(valueStr);
//						valueStr = "" + valueStr;
					}
					else if(attrName == "text"){
						valueStr = valueStr.replace(/</gi, "&lt;");
						valueStr = valueStr.replace(/>/gi, "&gt;");
						valueStr = valueStr.replace(/\"/gi, "&quot;");//引号替换
					}
					else if(attrName == "sizeGrid"){
						var gridArr:Array = valueStr.split(",");
						if(gridArr.length){
							valueStr = gridArr[1] + "," + gridArr[2] + "," + gridArr[3] + "," + gridArr[0];
						}
					}
					else if(tag == "UIView" && attrName == "source"){
						attrName = "editorInfo";
						valueStr = valueStr.replace(".xml", ".ui");
						viewSource = "mobile/" + valueStr;
//						viewSource = "" + valueStr;
						valueStr = "";
						
					}
					else if(tag=="Label" && attrName=="size"){
						attrName = "fontSize";
					}
					else if(attrName=="labelColors"){
						valueStr = valueStr.replace(/0x/gi, "#");
					}
//					else if(attrName=="multiline"){
//						attrName="wordWrap";
//					}
					else if(attrName=="labelStroke"){
						var strokeArr:Array = valueStr.split(",");
//						if(strokeArr[4] != null){
//							valueStr = strokeArr[4];
//						}
//						else{
//							valueStr = 1 + "";
//						}
						valueStr = 1 + "";
						labelStrokeColorStr = ColorUtil.colToStr(strokeArr[0]);
						valueStr += "," + "\"labelStrokeColor\":\"" + labelStrokeColorStr + "\"";
					}
					else if(attrName=="vScrollBarSkin"){//滚动条的皮肤转换
						//mobile/a_common_v1/vscroll
						//png.a_common_v1.vscroll
						valueStr = valueStr.replace(/\./g,"/");
						valueStr = valueStr.replace("png","mobile")+".png";
					}
					else if(attrName=="scale"){//将缩放改为laya的scaleXY的属性
						attrName="scaleXY";
					}
					
					if(attrName == "width" || attrName == "height" || attrName == "x" || attrName == "y" || attrName == "stroke"
						|| attrName == "visible" || attrName == "alpha" || attrName == "mouseEnabled" || attrName == "privotX" || attrName == "privotY"
						|| attrName == "visible" || attrName == "height" || attrName == "height" || attrName == "height" || attrName == "height"
					 	|| attrName == "fontSize" || attrName=="labelSize" || attrName=="mouseThrough"){
						isInt = true;
//						valueStr = valueStr.replace(/\./gi, "");//有的时候值会是"300."，会报错，所以转成"300"
						//去掉开头和结尾的点号
						if(valueStr.charAt(0)==".") valueStr = valueStr.substring(1);
						if(valueStr.charAt(valueStr.length-1)==".") valueStr = valueStr.substr(0,valueStr.length-1);
					}
					else{
						isInt = false;
					}
					
					if(propsStr == ""){
						propsStr = "{";
					}
					if(attrName == "mouseEnabled"){//兼容flash
						propsStr += jsStr("flashMouseEnabled", valueStr, isInt);
					}
					else if(labelStrokeColorStr){
						propsStr += jsStr(attrName, valueStr, true);
					}
					else{
						propsStr += jsStr(attrName, valueStr, isInt);
					}
					
					if(i != xl.length() - 1)
					{
						propsStr += ",";
					}
					else{
						propsStr += "}";
					}
				}
				
				var isLinkBtn:Boolean = false;
				if(tag == "LinkButton"){
					tag = "Button";
					isLinkBtn = true;
				}
				obj = {
					"x":_posX,
					"type":toJs(tag),
					"nodeParent":_posX == 0 ? -1 : 1,
					"label":(varName == "" ? toJs(tag) : toJs(tag + "("+varName+")")),
					"isDirectory":_posX == 0 ? true : false,
					"isAniNode":true,
					"hasChild":false,
					"compId":4
				};
				if(_posX == 0){
					obj["isOpen"] = true;
					obj["selectedBox"] = 1;
					obj["selecteID"] = SELECTEID;
				}
				if(!propsStr){//说明是空的xml
					return;
				}
				obj["props"] = JSON.parse(propsStr);
				if(isLinkBtn){
					obj["props"]["runtime"] = "zxk.ZLinkButton";
				}
				if(viewSource != ""){
					obj["source"] = viewSource;
				}
				
				arr.push(obj);
				
				if(singleIndex != -1 && singleIndex < indexEnter)//说明是单行标签，没有子对象
				{
					startIndex = indexEnter + 3;
				}
				else//说明有子对象
				{
					var tag2:String = "</" + tag + ">";
					var endIndex:int = 0;
					//依据对比左侧的间距来对应XML块，很搓就是干
					var leftSpacing:int = 0;
					if(startIndex == 0){
						leftSpacing = index;
					}
					else{
						var preEnter1:int = xml.lastIndexOf("\n", index);
						leftSpacing = index - preEnter1 - 1;
					}
					var stepIndex:int = index + 1;
					var leftSpacing2:int;
					while(true)
					{
						var tempIndex:int = xml.indexOf(tag2, stepIndex);
						var preEnter2:int = xml.lastIndexOf("\n", tempIndex);
						leftSpacing2 = tempIndex - preEnter2 - 1;
						if(leftSpacing2 != leftSpacing){
							stepIndex = tempIndex + tag2.length;
						}
						else{
							endIndex = tempIndex;
							break;
						}
					}
					
					obj.child = [];
					var childXml:String = xml.substring(indexEnter + 1, endIndex);
					transferXML(childXml, obj.child);
					startIndex = endIndex + tag2.length;
				}
				
				if(startIndex >= xml.length - 6)//不知道为什么，减掉这个 误差。可能是空格或是什么，反正不管了拿起键盘就是干。
				{
					break;
				}
			}
			
			_posX += 15;
			_compId += 1;
			
		}
		/**
		 * 对应AssetsToLaya的转换。
		 */
		private function getLayaSkin(path:String):String
		{
			if(path.indexOf("a_test/") == -1){
				var arr:Array = path.split("mobile/");
				var arr2:Array = arr[1].split("/");
				var newpath:String = arr[0] + "mobile/";
				for(var i:int=0; i<arr2.length; i++){
					if(i == 0){
						newpath += arr2[i] + "/";
					}
					else if(i < arr2.length-1){
						newpath += arr2[i] + "&";
					}
					else{
						newpath += arr2[i];
					}
				}
			}
			else{
				newpath = path;
			}
			return newpath;
		}
		
		private function toJs(key:String):String
		{
			return key;
//			return "\"" + key + "\"";
		}
		private function jsStr(key:String, value:*, isInt:Boolean = false):String
		{
//			return key + ":" + value;
			if(isInt){
				return "\"" + key + "\":" + value;
			}
			else{
				return "\"" + key + "\":\"" + value + "\"";
			}
		}
	}
}

import flash.net.URLLoader;

class TextLoader extends URLLoader
{
	public var url:String;
	
	public function TextLoader()
	{
		super();
	}
}